package com.wechat.controller;

import com.wechat.utils.SignUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wuyunbin
 */
@RestController
@RequestMapping("/")
public class IndexController {

    private final Logger log= LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public void checkToken(HttpServletRequest request,HttpServletResponse response){
        //token验证代码段
        try{
            log.info("请求已到达，开始校验token");
            if (StringUtils.isNotBlank(request.getParameter("signature"))) {
                String signature = request.getParameter("signature");
                String timestamp = request.getParameter("timestamp");
                String nonce = request.getParameter("nonce");
                String echostr = request.getParameter("echostr");
                log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
                if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                    log.info("数据源为微信后台，将echostr[{}]返回！", echostr);
                    response.getOutputStream().println(echostr);
                }
            }
        }catch (IOException e){
            log.error("校验出错");
            e.printStackTrace();
        }

}

    @GetMapping("404")
    public String handleError(){
        return "404";
    }

    @RequestMapping(value = "/weChatRedirectUri",method = RequestMethod.GET)
    public void weChatRedirectUri(HttpServletRequest request){
        String code=request.getParameter("code");
        log.info("code="+code);
    }

}